<?php

// +---------------------------------------------+
// |     Copyright  2010 - 2018 InterPhoto       |
// |     http://www.weentech.com                 |
// |     This file may not be redistributed.     |
// +---------------------------------------------+

include('includes/Admin.Core.php');

CheckAccess('manageuser');


PrintHeader('用户管理');

$action = ForceIncomingString('action', 'displayusers');
if(IsPost('updateusers')) $action= 'updateusers';
if(IsPost('deleteusers')) $action= 'deleteusers';

$getusergroups = $DB->query("SELECT groupid, name FROM " . TABLE_PREFIX . "usergroups ORDER BY groupid");
while($usergroup = $DB->getrow($getusergroups)) {
	if($usergroup['groupid'] != 1) $usergroups[$usergroup['groupid']] = $usergroup['name'];
}

@set_time_limit(600);

// ################################ INSERT USER ################################

if($action == 'insertuser')
{
	$groupid     = ForceIncomingInt('groupid');
	$username        = ForceIncomingString('username');
	$password        = ForceIncomingString('password');
	$passwordconfirm = ForceIncomingString('passwordconfirm');
	$email           = ForceIncomingString('email');
	$userfullname        = ForceIncomingString('userfullname');
	$usercompany        = ForceIncomingString('usercompany');
	$useraddress        = ForceIncomingString('useraddress');
	$userpostcode        = ForceIncomingString('userpostcode');
	$usertel        = ForceIncomingString('usertel');
	$userfax        = ForceIncomingString('userfax');
	$useronline        = ForceIncomingString('useronline');
	$userwebsite        = ForceIncomingString('userwebsite');

	if(strlen($username) == 0){
		$errors[] = '请输入用户名!';
	}elseif(!IsName($username)){
		$errors[] = '用户名存在非法字符!';
	}elseif($registered = $DB->query_first("SELECT userid FROM " . TABLE_PREFIX . "users WHERE username = '$username'")){
		Errmsg('用户名已存在, 请重新输入!');
	}

	if(strlen($password) == 0){
		$errors[] = '请输入密码!';
	}elseif(!IsPass($password)){
		$errors[] = '密码存在非法字符!';
	}elseif($password != $passwordconfirm){
		$errors[] = '确认密码与原密码不相同!';
	}

	if(strlen($email) == 0){
		$errors[] = '请输入Email地址!';
	}elseif(!IsEmail($email)){
		$errors[] = 'Email地址不规范!';
	}elseif($DB->query_first("SELECT email FROM " . TABLE_PREFIX . "users WHERE email = '$email' ")){
		Errmsg('Email地址已被使用, 请重新输入!');
	}

	if(!isset($errors))
	{
		$DB->query("INSERT INTO " . TABLE_PREFIX . "users VALUES (NULL, '$groupid', 1, '$username', '".md5($password)."', '', '$email', '".time()."', 0, '$userfullname', '$usercompany', '$useraddress', '$userpostcode', '$usertel', '$userfax', '$useronline', '$userwebsite')");

		PrintRedirect('admin.users.php', 1);
	}
	else
	{
		PrintErrors($errors, '添加用户错误');
		$action = 'adduser';
	}
}

// ################################ UPDATE USER ################################

if($action == 'updateuser')
{
	$userid          = ForceIncomingInt('userid');
	$groupid     = ForceIncomingInt('groupid');
	$username        = ForceIncomingString('username');
	$password        = ForceIncomingString('password');
	$passwordconfirm = ForceIncomingString('passwordconfirm');
	$email           = ForceIncomingString('email');
	$activated       = ForceIncomingInt('activated');
	$userfullname        = ForceIncomingString('userfullname');
	$usercompany        = ForceIncomingString('usercompany');
	$useraddress        = ForceIncomingString('useraddress');
	$userpostcode        = ForceIncomingString('userpostcode');
	$usertel        = ForceIncomingString('usertel');
	$userfax        = ForceIncomingString('userfax');
	$useronline        = ForceIncomingString('useronline');
	$userwebsite        = ForceIncomingString('userwebsite');
	$deleteuser       = ForceIncomingInt('deleteuser');
	$deleteuserimages       = ForceIncomingInt('deleteuserimages');

	if($deleteuserimages){
		$getimages = $DB->query("SELECT imageid FROM " . TABLE_PREFIX . "images WHERE userid = '$userid' ");

		while($image = $DB->getrow($getimages)){
			DeleteImageById ($image['imageid']);
		}
	}
  
	if($deleteuser){
		if($userid == $userinfo['userid'])
		{
			$errors = "呵呵, 您无法删除自己!";
			PrintErrors($errors, '编辑用户错误');
			$action = 'edituser';
		}else{
			$DB->query("DELETE FROM " . TABLE_PREFIX . "users WHERE userid = '$userid' ");
			PrintRedirect('admin.users.php', 1);
		}
	}else{

		if(strlen($username) == 0){
			$errors[] = '请输入用户名!';
		}elseif(!IsName($username)){
			$errors[] = '用户名存在非法字符!';
		}elseif($DB->query_first("SELECT userid FROM " . TABLE_PREFIX . "users WHERE username = '$username' AND  userid != '$userid'")){
			Errmsg('用户名已存在, 请重新输入!');
		}

		if(strlen($password) OR strlen($passwordconfirm))
		{
			if(!IsPass($password)){
				$errors[] = '密码存在非法字符!';

			}elseif(strcmp($password, $passwordconfirm)){
				$errors[] = '确认密码与原密码不相同!';
			}
		}
	  
		if(strlen($email) == 0){
			$errors[] = '请输入Email地址!';
		}elseif(!IsEmail($email)){
			$errors[] = 'Email地址不规范!';
		}elseif($DB->query_first("SELECT email FROM " . TABLE_PREFIX . "users WHERE email = '$email' AND userid != '$userid'")){
			Errmsg('Email地址已被使用, 请重新输入!');
		}

	  
		if(!isset($errors))	{
			$DB->query("UPDATE " . TABLE_PREFIX . "users SET username    = '$username',
			".Iif($userid != $userinfo['userid'], "groupid = '$groupid', activated = '$activated',")."
			email       = '$email',
			userfullname       = '$userfullname',
			usercompany       = '$usercompany',
			useraddress       = '$useraddress',
			userpostcode       = '$userpostcode',
			usertel       = '$usertel',
			userfax       = '$userfax',
			useronline       = '$useronline',
			userwebsite       = '$userwebsite'												 
			WHERE userid      = '$userid'");

			if(strlen($password) > 0)
			{
				$DB->query("UPDATE " . TABLE_PREFIX . "users SET password = '" . md5($password) . "' WHERE userid = '$userid'");
			}

			PrintRedirect('admin.users.php', 1);
		}else{
			PrintErrors($errors, '编辑用户错误');
			$action = 'edituser';
		}
	}
}

// ############################### DELETE USERS ################################

if($action == 'deleteusers')
{
	$deleteuserids = ForceIncomingArray('deleteuserids');

	for($i = 0; $i < count($deleteuserids); $i++){
		if($deleteuserids[$i] != $userinfo['userid'])
		{
			$DB->query("DELETE FROM " . TABLE_PREFIX . "users WHERE userid = '" . ForceInt($deleteuserids[$i]) . "'");
		}else{
			$errors = "呵呵, 您无法删除自己!";
		}
	}

	if($errors){
		PrintErrors($errors, '删除用户错误');
		PrintRedirect('admin.users.php', 5);
	}else{
		PrintRedirect('admin.users.php', 1);
	}

}

// ############################### UPDATE USERS ################################

if($action == 'updateusers')
{
	$userids   = ForceIncomingArray('updateuserids');
	$activateds   = ForceIncomingArray('activateds');

    for($i = 0; $i < count($userids); $i++)
    {
		if($userids[$i] != $userinfo['userid']){
			$DB->query("UPDATE " . TABLE_PREFIX . "users SET activated = '$activateds[$i]' WHERE userid = '$userids[$i]'");
		}
    }

    PrintRedirect('admin.users.php', 1);

}

// ############################ DISPLAY USER FORUM #############################

if($action == 'edituser' OR $action == 'adduser')
{
	$userid = ForceIncomingInt('userid');

	if($userid){
		if(!$subcategory = $DB->query_first("SELECT userid FROM " . TABLE_PREFIX . "users WHERE userid = '$userid'")){
			PrintErrors('用户不存在或已删除!', '编辑用户错误');
		}
	}

	if(isset($errors))
	{
		// new user or edit user with errors, redisplaying the form
		$user = array('userid'   => $userid,
			  'groupid'  => Iif($userid == $userinfo['userid'], $userinfo['groupid'], $groupid),
			  'activated'  => Iif($userid == $userinfo['userid'], $userinfo['activated'], $activated),
			  'username'     => $username,
			  'email'     => $email,
			  'userfullname'     => $userfullname,
			  'usercompany'     => $usercompany,
			  'useraddress'     => $useraddress,
			  'userpostcode'     => $userpostcode,
			  'usertel'     => $usertel,
			  'userfax'     => $userfax,
			  'useronline'     => $useronline,
			  'userwebsite'     => $userwebsite);

	} else if($userid) {
		$user = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "users WHERE userid = '$userid'");
	}else{
		$user = array('userid' => 0, 'groupid' => 3, 'activated' => 1);
	}

	if($userid)
	{
		PrintSection('编辑用户: ' . $user['username']);
	}else{
		PrintSection('添加用户');
	}

	$message_info = '(<font class=ohred>必填项</font>)';
	$message_pass = Iif($userid, '(<font class=ohgreen>不修改请留空</font>)', $message_info);

	echo '<form method="post" action="admin.users.php">
	<input type="hidden" name="action" value="' . Iif($userid, 'updateuser', 'insertuser') . '" />
	<input type="hidden" name="userid" value="' . $user['userid'] . '" />
	<table width="100%" border="0" cellpadding="5" cellspacing="0">
	<tr>
	<td class="tdrow2" width="40%">所属用户群组:</td>
	<td class="tdrow3"><select name="groupid" ' . Iif($userid == $userinfo['userid'], 'disabled') .'>';

	foreach($usergroups as $key => $value)
	{
		echo '<option value="' . $key . '" ' . Iif($user['groupid'] == $key, ' SELECTED') . '>' . $value . '</option>';
	}

	echo '</select>
	</td>
	</tr>
	<tr>
	<td class="tdrow2" width="40%">用户名'.$message_info.':</td>
	<td class="tdrow3"><input type="text" name="username" value="'.$user['username'].'" size="40" /></td>
	</tr>
	<tr>
	<td class="tdrow2">密码'.$message_pass.':</td>
	<td class="tdrow3"><input type="password" name="password" size="40" /></td>
	</tr>
	<tr>
	<td class="tdrow2">确认密码'.$message_pass.':</td>
	<td class="tdrow3"><input type="password" name="passwordconfirm" size="40" /></td>
	</tr>
	<tr>
	<td class="tdrow2">Email地址'.$message_info.':</td>
	<td class="tdrow3"><input type="text" name="email" value="'.$user['email'].'" size="40" /></td>
	</tr>
	<tr>
	<td class="tdrow2">真实姓名:</td>
	<td class="tdrow3"><input type="text" name="userfullname" value="'.$user['userfullname'].'" size="40" /></td>
	</tr>
	<tr>
	<td class="tdrow2">单位名称:</td>
	<td class="tdrow3"><input type="text" name="usercompany" value="'.$user['usercompany'].'" size="40" /></td>
	</tr>
	<tr>
	<td class="tdrow2">通讯地址:</td>
	<td class="tdrow3"><input type="text" name="useraddress" value="'.$user['useraddress'].'" size="40" /></td>
	</tr>
	<tr>
	<td class="tdrow2">邮编:</td>
	<td class="tdrow3"><input type="text" name="userpostcode" value="'.$user['userpostcode'].'" size="40" /></td>
	</tr>
	<tr>
	<td class="tdrow2">电话:</td>
	<td class="tdrow3"><input type="text" name="usertel" value="'.$user['usertel'].'" size="40" /></td>
	</tr>
	<tr>
	<td class="tdrow2">传真:</td>
	<td class="tdrow3"><input type="text" name="userfax" value="'.$user['userfax'].'" size="40" /></td>
	</tr>
	<tr>
	<td class="tdrow2">在线联系:</td>
	<td class="tdrow3"><input type="text" name="useronline" value="'.$user['useronline'].'" size="40" /></td>
	</tr>
	<tr>
	<td class="tdrow2">网址:</td>
	<td class="tdrow3"><input type="text" name="userwebsite" value="'.$user['userwebsite'].'" size="40" /></td>
	</tr>';

	if($userid){
		echo '<tr>
		<td class="tdrow2">是否激活?</td>
		<td class="tdrow3"><input type="checkbox" ' . Iif($userid == $userinfo['userid'], 'disabled') .' name="activated" value="1" ' . Iif($user['activated'] == 1, ' checked="checked"') .' /></td>
		</tr>
		<tr>
		<td class="tdrow2">删除此用户?</td>
		<td class="tdrow3"><input type="checkbox" ' . Iif($userid == $userinfo['userid'], 'disabled') .' name="deleteuser" value="1" />&nbsp;(<font class=ohredb>慎选</font>)</td>
		</tr>
		</tr>
		<tr>
		<td class="tdrow2">删除此用户的所有图片?</td>
		<td class="tdrow3"><input type="checkbox" name="deleteuserimages" value="1" />&nbsp;(<font class=ohredb>慎选</font>)</td>
		</tr>';
	}
		
	echo '<tr>
	<td class="tdrow1" bgcolor="#FCFCFC" colspan="2" align="center">
	<input type="submit" value="' . Iif($userid, '保存更新', '提交保存') . '" />
	</td>
	</tr>
	</table>
	</form>';

	EndSection();
}

// ############################### DISPLAY USERS ###############################

if($action == 'displayusers')
{
	$NumPerPage =20;

	$page = ForceIncomingInt('page', 1);
	$letter = ForceIncomingString('letter');
	$searchname = ForceIncomingString('searchname');
	$searchemail = ForceIncomingString('searchemail');
	$searchgroup = ForceIncomingInt('searchgroup');

	if(IsGet('searchname') OR IsGet('searchemail') ){
		$searchname = urldecode($searchname);
		$searchemail = urldecode($searchemail);
	}

	$start = $NumPerPage * ($page-1);

	PrintSection('快速查找用户');
	echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
	<tr>
	<td class="tdrow1" align="center">
	<a href="admin.users.php">全部用户</a>&nbsp;';

	for($alphabet = 'a'; $alphabet != 'aa'; $alphabet++)
	{
		echo '<a href="admin.users.php?letter=' . $alphabet . '">' . strtoupper($alphabet) . '</a> &nbsp;';
	}

	echo '&nbsp;<a href="admin.users.php?letter=Validating">未激活</a>&nbsp;
	<a href="admin.users.php?letter=Neverlogin">未登陆</a>&nbsp;
	<a href="admin.users.php?letter=Other">中文名</a></td>
	</tr>
	</table>';
	EndSection();

	PrintSection('搜索用户');
	echo '<form method="post" action="admin.users.php" name="searchusers">
    <input type="hidden" name="letter" value="Search" />
	<table width="100%" border="0" cellpadding="5" cellspacing="0">
	<tr>
	<td class="tdrow1" align="center">用户名:&nbsp;<input type="text" name="searchname" size="12">&nbsp;&nbsp;Email地址:&nbsp;<input type="text" name="searchemail" size="16">&nbsp;&nbsp;用户组:&nbsp;<select name="searchgroup"><option value="0">所有用户组</option>';

	foreach($usergroups as $key => $value)
	{
		echo '<option value="' . $key . '">' . $value . '</option>';
	}

	echo '</select>&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="搜索用户" /></td>
	</tr>
	</table></form>';
	EndSection();

	$searchsql = '';

	if(isset($letter) AND $letter != '')
	{
		if($letter == 'Other')
		{
			$searchsql = " WHERE u.username NOT REGEXP(\"^[a-zA-Z]\") ";
			$title = '使用中文用户名的用户';
		}
		else if($letter == 'Validating')
		{
			$searchsql = " WHERE u.activated = 0 ";
			$title = '尚未激活的用户';
		}
		else if($letter == 'Search')
		{
			$searchsql = " WHERE u.username LIKE '%".$searchname."%' AND u.email LIKE '%".$searchemail."%' ".Iif($searchgroup, " AND u.groupid = '$searchgroup'");
			$title = '搜索到的用户';
		}
		else if($letter == 'Neverlogin')
		{
			$searchsql = " WHERE u.lastactivity = 0 ";
			$title = '从未登陆的用户';
		}
		else
		{
			$searchsql = " WHERE u.username LIKE '$letter%' ";
			$title = strtoupper($letter) . ' 字母开头的用户';
		}
    
	}else{
		$title = '全部用户列表';
	}

	$getusers = $DB->query("SELECT u.userid, u.groupid, u.username, u.email, u.activated, u.joindate, u.lastactivity, COUNT(i.imageid) AS images FROM " . TABLE_PREFIX . "users u LEFT JOIN " . TABLE_PREFIX . "images i ON (u.userid = i.userid) ".$searchsql." GROUP BY u.userid ORDER BY u.activated ASC, u.userid DESC LIMIT $start,$NumPerPage");
	$maxrows = $DB->query_first("SELECT COUNT(u.userid) AS value FROM " . TABLE_PREFIX . "users u ".$searchsql);

	echo '&nbsp;&nbsp;&nbsp;&nbsp;<a href="admin.users.php?action=adduser"><img src="'.TEMPLATEPATH.'images/open.gif" align="absmiddle"> <font class=ohblueb><u>添加用户</u></font></a>';

	PrintSection($title.'('.$maxrows['value'].'个)');

	echo '<form method="post" action="admin.users.php" name="deleteusers">
	<table width="100%" border="0" cellpadding="5" cellspacing="0">
	<tr>
	<td class="tdrow1" nowrap="nowrap">用户名</td>
	<td class="tdrow1" nowrap="nowrap">用户组</td>
	<td class="tdrow1" nowrap="nowrap">状态</td>
	<td class="tdrow1" nowrap="nowrap">图片数</td>
	<td class="tdrow1" nowrap="nowrap">Email地址</td>
	<td class="tdrow1" nowrap="nowrap">注册日期</td>
	<td class="tdrow1" nowrap="nowrap">最后登陆</td>
	<td class="tdrow1" nowrap="nowrap"><input type="checkbox" checkall="group" onclick="javascript: return select_deselectAll (\'deleteusers\', this, \'group\');"> 删除</td>
	</tr>';

	if($maxrows['value'] < 1){
		echo '<tr><td class="tdrow3" colspan="8" align="center" height="48" valign="middle"><font class=ohredb>未搜索到任何用户!</font></td></tr>';
	}else{
		while($user = $DB->getrow($getusers))
		{
			
			echo '<tr>
			<td class="tdrow2"><input type="hidden" name="updateuserids[]" value="'.$user['userid'].'" />
			<a href="admin.users.php?action=edituser&userid='.$user['userid'].'">
			'.Iif($user['activated'] != '1','<font class=ohred><u>').$user['username'].Iif($user['activated'] != '1','</u></font>').'</a>
			</td>
			<td class="tdrow3">' . $usergroups[$user['groupid']] . '</td>
			<td class="tdrow2">
			<select name="activateds[]">
			<option value="1">已激活</option>
			<option style="color:red;" value="0" ' . Iif(!$user['activated'], 'SELECTED', '') . '>未激活</option>
			</select>
			</td>
			<td class="tdrow3">' . $user['images'] . '</td>
			<td class="tdrow2">' . Iif($user['userid'] != $userinfo['userid'], '<a href="mailto:' . $user['email'] . '">' . $user['email'] . '</a>', $user['email']) . '</td>
			<td class="tdrow3">' . DisplayDate($user['joindate'], 'Y-m-d') . '</td>
			<td class="tdrow2">';

			if($user['lastactivity'] == 0)
			{
				echo '<span class="ohorange">从未登陆</span>';
			}
			else 
			{
				echo DisplayDate($user['lastactivity'], 'Y-m-d');
			}

			echo '</td>
			<td class="tdrow3"><input type="checkbox" name="deleteuserids[]" value="' . $user['userid'] . '" checkme="group" ' . Iif($user['userid'] == $userinfo['userid'], 'disabled') .'/></td>
			</tr>';
		}
	}

	$totalpages = ceil($maxrows['value'] / $NumPerPage);

	if($totalpages > 1){
		echo '<tr><td class="tdrow3" colspan="8" align="center" height="48" valign="middle">';
		echo GetPageList('admin.users.php', $totalpages, $page, 10, 'letter', $letter, 'searchname', urlencode($searchname), 'searchemail', urlencode($searchemail), 'searchgroup', $searchgroup);
		echo '</td></tr>';
	}

	echo '<tr><td class="tdrow1" colspan="8" align="center"><input type="submit" name="updateusers" value=" 保存更新 " />&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" name="deleteusers" onclick="return confirm(\'确定删除所选用户吗?\r\n\r\n提示: 这里删除用户, 用户的图片不会删除!\');" value=" 删除用户 " /></td></tr></table></form>';

	EndSection();
}


// ############################### PRINT FOOTER ################################

PrintFooter();

?>